package com.treetao.union.mall.api.vo.req;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.treetao.union.core.exception.DevMException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ReqParam extends HashMap<String, String> implements Serializable{
	private static final long serialVersionUID = -8874071598857011098L;
	
	private HttpServletRequest getRequest() {
	    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
	    return servletRequestAttributes.getRequest();
	}
	
	public ReqParam() {
		HttpServletRequest req = getRequest();
		Enumeration<String> names = req.getParameterNames();
		while(names.hasMoreElements()) {
			String key = names.nextElement();
			String value = req.getParameter(key);
			put(key, value); 
			log.info("请求参数：{} - {} - {}",names.hashCode(), key,value);
		}
	}
	
	public static ReqParam convert(Map<String, String> map) {
		ReqParam rp = new ReqParam();
        
	    Iterator<Entry<String, String>> it=map.entrySet().iterator(); 
	    while(it.hasNext()) { 
	        @SuppressWarnings("rawtypes")
			Map.Entry entry=(Map.Entry)it.next(); 
	        Object key=entry.getKey(); 
	        if(key!=null && map.get(key)!=null) { 
	        	rp.put(key.toString(), map.get(key)); 
	        } 
	    } 
	    return rp;
	}

	public String getValue(String key, Boolean... nullable) {
		String value = get(key);
		if("undefined".equals(value) || "".equals(value)) {
			value = null;
		}
		if (nullable != null && nullable.length>0 && !nullable[0]) {
			if (value == null || value.length() == 0 || "undefined".equals(value)) {
				throw new DevMException(key + "不能为空");
			}
		}
		return value;
	}

	public Boolean getBoolean(String key, Boolean... nullable) {
		String value = getValue(key, nullable);
		return null == value ? null : Boolean.valueOf(value);
	}

	public Long getLong(String key, Boolean... nullable) {
		String value = getValue(key, nullable);
		return null == value ? null : Long.valueOf(value);
	}

	public Integer getInt(String key, Boolean... nullable) {
		String value = getValue(key, nullable);
		return null == value ? null : Integer.valueOf(value);
	}

	public Double getDouble(String key, Boolean... nullable) {
		String value = getValue(key, nullable);
		return null == value ? null : Double.valueOf(value);
	}

	public long getPageSize() {
		Long size = getLong("size");
		return size == null ? 10 : size;
	}

	public long getPageCurrent() {
		Long current = getLong("current");
		return current == null ? 1 : current;
	}

}
